const jwt = require('jsonwebtoken');
const { query } = require('../config/database');

// JWT令牌验证中间件
const authenticateToken = async (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN

  if (!token) {
    return res.status(401).json({ error: '访问令牌缺失' });
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    
    // 验证用户是否存在且状态正常
    const users = await query(
      'SELECT id, username, email, nickname, avatar, status FROM users WHERE id = ? AND status = 1',
      [decoded.userId]
    );

    if (users.length === 0) {
      return res.status(401).json({ error: '用户不存在或已被禁用' });
    }

    req.user = users[0];
    next();
  } catch (error) {
    console.error('Token验证失败:', error);
    return res.status(403).json({ error: '访问令牌无效' });
  }
};

// 可选的JWT验证中间件（不强制要求登录）
const optionalAuth = async (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    req.user = null;
    return next();
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    const users = await query(
      'SELECT id, username, email, nickname, avatar, status FROM users WHERE id = ? AND status = 1',
      [decoded.userId]
    );

    req.user = users.length > 0 ? users[0] : null;
  } catch (error) {
    req.user = null;
  }

  next();
};

// 管理员权限验证
const requireAdmin = async (req, res, next) => {
  if (!req.user) {
    return res.status(401).json({ error: '需要登录' });
  }

  // 这里可以根据实际需求添加管理员判断逻辑
  // 例如检查用户角色或特定权限
  if (req.user.id !== 1) { // 简单示例：ID为1的用户是管理员
    return res.status(403).json({ error: '需要管理员权限' });
  }

  next();
};

module.exports = {
  authenticateToken,
  optionalAuth,
  requireAdmin
};